<?php

namespace app\api\logic;
use app\admin\logic\BasicLogic;
use app\shop\logic\ShopLogic;
use think\facade\Config;
use app\data\util\HttpUtil;
use think\facade\Db;

class ShopifyLogic extends BasicLogic
{

    /**
     * @desc 手动发货
     * @date   2024-07-09
     */
    public function ManualShipping($data=[]){
        if(empty($data['order_id'])){
            return  $this->jsonMessage(201,'true','订单号order_id为空',null);
        }
        if(empty($data['number'])){
            return  $this->jsonMessage(201,'true','物流单号number为空',null);
        }
        $order_id = $data['order_id'];
        $number = $data['number'];
        $site_id = $data['site_id'] ?? 121;

        $site = Db::connect('DULIZHAN')
            ->name('site')
            ->where('id', $site_id)
            ->find();

            
        //测试订单详情
        // $url = $site['site_url'] . "/admin/api/2023-07/orders/6033337057341.json";
        // $ldata = HttpUtil::shopifyGetUrl($url, $site['apikey'], $site['apisecret']);
        // $ldata2 = json_decode($ldata, true);
        // halt($ldata2);
        
        //获取履行订单id
        $fulfillment_order_id = 0;

        $url = $site['site_url'] . "/admin/api/2023-07/orders/".$order_id."/fulfillment_orders.json";
        $fulfillment_orders = HttpUtil::shopifyGetUrl($url, $site['apikey'], $site['apisecret']);
        $fulfillment_orders = json_decode($fulfillment_orders, true);
        if(!empty($fulfillment_orders['fulfillment_orders'][0]['id']) && isset($fulfillment_orders['fulfillment_orders'][0]['id'])){
            $fulfillment_order_id = $fulfillment_orders['fulfillment_orders'][0]['id'];
        }
        if(!empty($fulfillment_order_id)){
            //物流id
            $url = $site['site_url'] . "/admin/api/2023-10/fulfillments.json";
            $data_fulfillments3['notify_customer'] = false;
            $data_fulfillments3['tracking_info']['company'] = "USPS";
            $data_fulfillments3['tracking_info']['number'] = $number;
            $data_fulfillments3['line_items_by_fulfillment_order'][0]['fulfillment_order_id'] = $fulfillment_order_id;
            $data_fulfillments['fulfillment'] = $data_fulfillments3;
            $return = HttpUtil::shopifyPostUrl($url,$data_fulfillments, $site);
            $return = json_decode($return, true);
            if(!empty($return['errors']) || !empty($return['error'])){
                return  $this->jsonMessage(201,'true','发货失败',null);
            }else{
                return  $this->jsonMessage(200,'true','发货成功',null);
            }
        }
        return  $this->jsonMessage(201,'true','没有物流信息',null);
    }

}